package com.iqilu.ksd.fragment;

import android.Manifest;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.tedcoder.wkvideoplayer.constant.VideoType;
import com.android.tedcoder.wkvideoplayer.model.Video;
import com.android.tedcoder.wkvideoplayer.model.VideoUrl;
import com.android.tedcoder.wkvideoplayer.view.MediaController;
import com.android.tedcoder.wkvideoplayer.view.SuperVideoPlayer;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.MainActivity;
import com.iqilu.ksd.adapter.TVChannelAdapter;
import com.iqilu.ksd.bean.TVBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.event.FragmentChangeEvent;
import com.iqilu.ksd.event.StopPlayRadioEvent;
import com.iqilu.ksd.event.StopPlayVideoEvent;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.utils.TVUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/15.
 */

public class TVListFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "TVListFragment";
    private static final String urlTemplate = "http://liveauth.iqilu.com/get_url?e=%s&s=%s&t=%s";

    private TVBean tvBean;
    private ArrayList<TVBean> list;
    private ArrayList<TVBean> tvList;
    private TVChannelAdapter adapter;

    private ImageView bgPlayer;
    private ImageView btPlay;
    private SuperVideoPlayer superVideoPlayer;
    private CommonTabLayout tabMenu;
    private FrameLayout layContent;
    private ListView lvList;
    private RelativeLayout layLoading;

    private int mTop;

    private static final int PERM_PHONE = 1001;

    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        @Override
        public void onCloseVideo() {
        }

        @Override
        public void onSwitchPageType() {
            if (getActivity().getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                resetPageToPortrait();
            } else {
                resetPageToLandscape();
            }
        }

        @Override
        public void onPlayFinish() {

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tvlist, null);
        bgPlayer = getView(view, R.id.bg_player);
        btPlay = getView(view, R.id.bt_play);
        superVideoPlayer = getView(view, R.id.superVideoPlayer);
        tabMenu = getView(view, R.id.tab_menu);
        layContent = getView(view, R.id.lay_content);
        layLoading = getView(view, R.id.lay_loading);
        tvBean = TVUtils.getWeiShi();
        btPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo();
            }
        });
        tvList = TVUtils.getTvList();
        lvList = getView(view, R.id.lv_list);
        adapter = new TVChannelAdapter(context, "tv");
        lvList.setAdapter(adapter);
        adapter.setData(tvList);
        adapter.notifyDataSetChanged();
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvBean = tvList.get(position);
                playVideo();
            }
        });
        mTop = superVideoPlayer.getTop();
        getList();
        return view;
    }

    private void getList() {
        String url = Api.URL_VIDEO_CHANNEL;
        OkHttpUtils.get().url(url).tag(context).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                adapter.setData(tvList);
                adapter.notifyDataSetChanged();
                layLoading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<TVBean> mList = null;
                list = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<TVBean>>() {
                });
                mList = setPlaying(tvList, list);
                adapter.setData(mList);
                adapter.notifyDataSetChanged();
                layLoading.setVisibility(View.GONE);
            }
        });
    }

    private ArrayList<TVBean> setPlaying(ArrayList<TVBean> local, ArrayList<TVBean> remote) {
        if (remote == null || remote.size() == 0 || remote.size() < local.size()) {
            return local;
        }
        for (int i = 0; i < local.size(); i++) {
            for (int j = 0; j < remote.size(); j++) {
                if (local.get(i).getId() == remote.get(j).getId()) {
                    local.get(i).setPlaying(remote.get(j).getPlaying());
                    local.get(i).setImg(remote.get(j).getImg());
                    break;
                }
            }
        }
        return local;
    }

    public void stop() {
        if (superVideoPlayer != null) {
            superVideoPlayer.pausePlay(false);
        }
    }

    private void playVideo() {
        if (NetworkUtils.isWifiConnected(context)) {
            toPlay();
        } else if (NetworkUtils.isAvailable(context)) {
            showSelectDialog();
        } else {
            toPlay();
        }
    }

    @AfterPermissionGranted(PERM_PHONE)
    public void toPlay() {
        String perm = Manifest.permission.READ_PHONE_STATE;
//        if (EasyPermissions.hasPermissions(context, perm)) {
            btPlay.setVisibility(View.GONE);
            superVideoPlayer.setVisibility(View.VISIBLE);
            superVideoPlayer.setAutoHideController(true);
            superVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
            Video video = new Video();
            VideoUrl videoUrl = new VideoUrl();
            videoUrl.setFormatName("480P");
            videoUrl.setFormatUrl(tvBean.getUrl());
//            videoUrl.setFormatUrl(getUrl(tvBean));
            videoUrl.setPath(tvBean.getPath());
            ArrayList<VideoUrl> arrayList1 = new ArrayList<>();
            arrayList1.add(videoUrl);
            video.setVideoName(getString(tvBean.getTitleResorceId()));
            video.setVideoUrl(arrayList1);
            video.setmVideoType(VideoType.VIDEO_LIVE);
            ArrayList<Video> videoArrayList = new ArrayList<>();
            videoArrayList.add(video);
            superVideoPlayer.loadMultipleVideo(videoArrayList, 0, 0, 0);
            adapter.setCurId(tvBean.getId());
            adapter.notifyDataSetChanged();
            EventBus.getDefault().post(new StopPlayRadioEvent());
//        } else {
//            EasyPermissions.requestPermissions(context, getString(R.string.per_con_phonestate), PERM_PHONE, perm);
//        }
    }

    private void showSelectDialog() {
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.content(getString(R.string.not_wifi))
                .btnText(getString(R.string.cancel), getString(R.string.continue_play))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        toPlay();
                        dialog.dismiss();
                    }
                }
        );
    }

    /***
     * 恢复屏幕至竖屏
     */
    public void resetPageToPortrait() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ((TVFragment) getParentFragment()).toggleHide(View.VISIBLE);
        ((MainActivity) getActivity()).toggleHide(View.VISIBLE);
        int width = ScreenUtils.getScreenWidth(context);
        int height = ConvertUtils.dp2px(context, 220);
        superVideoPlayer.getLayoutParams().height = (int) height;
        superVideoPlayer.getLayoutParams().width = (int) width;
        superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
    }

    /**
     * 恢复屏幕至横屏
     */
    public void resetPageToLandscape() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        superVideoPlayer.setPageType(MediaController.PageType.EXPAND);
        ((TVFragment) getParentFragment()).toggleHide(View.GONE);
        ((MainActivity) getActivity()).toggleHide(View.GONE);
        // 重新设置播放器的大小
        int height = ScreenUtils.getScreenWidth(context);
        int width = ScreenUtils.getScreenHeight(context);
        superVideoPlayer.getLayoutParams().height = (int) width;
        superVideoPlayer.getLayoutParams().width = (int) height;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_live_additem))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StopPlayVideoEvent event) {
        stop();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(FragmentChangeEvent event){
        if(superVideoPlayer == null) return;
        if(event.getId() == R.id.radio_news){
            superVideoPlayer.setTop(2000);
        }else {
            superVideoPlayer.setTop(mTop);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
